home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / lcppb.zip / LCPP04.ZIP / SWAP.CPP < prev    next >
C/C++ Source or Header  |  1991-07-04  |  2KB  |  74 lines

  1. // swap.cpp -- Use pointers to swap any two same-size variables
  2.  
  3. //#include <stream.hpp>
  4. #include <iostream.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7.  
  8. struct rec {         // Sample structure to swap
  9.   char *title;
  10.   char *author;
  11.   int pages;
  12. };
  13.  
  14. /* -- Function prototypes */
  15.  
  16. void swapbytes(void *p1, void *p2, unsigned size);
  17.  
  18. void showrecs(char *s);
  19.  
  20. rec r1, r2;          // Two rec global variables
  21.  
  22. main()
  23. {
  24.  
  25. /* -- Assign test values to the global variables */
  26.  
  27.   r1.title = "The C++ Programming Language";
  28.   r1.author= "Bjarne Stroustrup";
  29.   r1.pages = 328;
  30.   r2.title = "Mastering Turbo Pascal 5.5";
  31.   r2.author= "Tom Swan";
  32.   r2.pages  = 877;
  33.  
  34. /* -- Display variables before and after swapping */
  35.  
  36.   showrecs("Before");
  37.   swapbytes(&r1, &r2, sizeof(r1));
  38.   showrecs("After");
  39. }
  40.  
  41. /* -- Swap size bytes addressed by p1 and p2 */
  42.  
  43. void swapbytes(void *p1, void *p2, unsigned size)
  44. {
  45.   unsigned char t;     // Temporary place to hold each byte
  46.  
  47.   while (size-- > 0) {
  48.     t = *(char *)p1;
  49.     *((char *)p1)++ = *(char *)p2;
  50.     *((char *)p2)++ = t;
  51.   }
  52. }
  53.  
  54. /* -- Display values of r1 and r2 */
  55.  
  56. void showrecs(char *s)
  57. {
  58.   cout << "\n\n" << s << "\n============";
  59.   cout << "\nr1.title  = "   << (r1.title);
  60.   cout << "\nr1.author = "   << (r1.author);
  61.   cout << "\nr1.pages  = "   << (r1.pages);
  62.   cout << "\n\nr2.title  = " << (r2.title);
  63.   cout << "\nr2.author = "   << (r2.author);
  64.   cout << "\nr2.pages  = "   << (r2.pages) << '\n';
  65. }
  66.  
  67.  
  68. // Copyright (c) 1990 by Tom Swan. All rights reserved
  69. // Revision 1.00    Date: 08/30/1990   Time: 07:37 am
  70.  
  71. // Revision 1.01    Date: 07/03/1991   Time: 04:00 pm
  72. // Converted for Borland C++ 2.0
  73.  
  74.